package com.minidb.storage;

import com.minidb.utils.Constants;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class Page {
    private final int id;
    private final String tableName;
    private boolean dirty;
    private final List<List<String>> records;

    public Page(int id, String tableName) {
        this.id = id;
        this.tableName = tableName;
        this.records = new ArrayList<>();
        this.dirty = false;
    }

    public int getId() { return id; }
    public String getTableName() { return tableName; }
    public List<List<String>> getRecords() { return records; }
    public boolean isDirty() { return dirty; }
    public void setDirty(boolean dirty) { this.dirty = dirty; }

    public boolean addRecord(List<String> record) {
        // 添加空记录验证
        if (record == null || record.isEmpty()) {
            return false; // 拒绝空记录
        }
        
        // 检查是否所有字段都为空
        boolean allEmpty = true;
        for (String field : record) {
            if (field != null && !field.trim().isEmpty()) {
                allEmpty = false;
                break;
            }
        }
        if (allEmpty) {
            return false; // 拒绝所有字段都为空的记录
        }
        
        // 简化：每条记录序列化后长度 < PAGE_SIZE/4
        int estSize = estimateSize(record);
        if (getCurrentSize() + estSize > Constants.PAGE_SIZE - 128) return false;
        records.add(new ArrayList<>(record));
        dirty = true;
        return true;
    }

    private int estimateSize(List<String> rec) {
        int sum = 0;
        for (String s : rec) sum += (s == null ? 0 : s.length() * 2 + 4);
        return sum;
    }

    private int getCurrentSize() {
        int size = 0;
        for (List<String> rec : records) size += estimateSize(rec);
        return size;
    }

    /** 序列化为固定大小字节数组（简单实现） */
    public byte[] toBytes() {
        ByteBuffer buf = ByteBuffer.allocate(Constants.PAGE_SIZE);
        buf.putInt(id);
        buf.putInt(records.size());
        for (List<String> rec : records) {
            buf.putInt(rec.size());
            for (String v : rec) {
                byte[] data = v.getBytes();
                buf.putInt(data.length);
                buf.put(data);
            }
        }
        return buf.array();
    }

    /** 从字节数组反序列化 */
    public static Page fromBytes(byte[] bytes, String tableName) {
        ByteBuffer buf = ByteBuffer.wrap(bytes);
        int id = buf.getInt();
        int count = buf.getInt();
        Page p = new Page(id, tableName);
        for (int i = 0; i < count; i++) {
            int colNum = buf.getInt();
            List<String> rec = new ArrayList<>();
            for (int j = 0; j < colNum; j++) {
                int len = buf.getInt();
                byte[] data = new byte[len];
                buf.get(data);
                rec.add(new String(data));
            }
            p.records.add(rec);
        }
        return p;
    }
}
